package com.xgkj.diyiketang.yizhibo;

import android.Manifest;
import android.animation.ObjectAnimator;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.SurfaceTexture;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.TextureView;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AnimationSet;
import android.view.animation.ScaleAnimation;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.easyvaas.sdk.core.bean.StreamInfoEntity;
import com.easyvaas.sdk.core.net.ApiHelper;
import com.easyvaas.sdk.core.net.MyRequestCallBack;
import com.easyvaas.sdk.core.util.Logger;
import com.easyvaas.sdk.live.base.EVStreamerParameter;
import com.easyvaas.sdk.live.base.OnErrorListener;
import com.easyvaas.sdk.live.base.OnInfoListener;
import com.easyvaas.sdk.live.base.audio.EVBgmPlayer;
import com.easyvaas.sdk.live.base.interactive.OnInteractiveLiveListener;
import com.easyvaas.sdk.live.base.view.CameraPreview;
import com.easyvaas.sdk.live.base.view.CameraTextureView;
import com.easyvaas.sdk.live.wrapper.EVLive;
import com.easyvaas.sdk.live.wrapper.LiveConstants;
import com.sina.weibo.sdk.api.TextObject;
import com.sina.weibo.sdk.api.WebpageObject;
import com.sina.weibo.sdk.api.WeiboMultiMessage;
import com.sina.weibo.sdk.api.share.BaseResponse;
import com.sina.weibo.sdk.api.share.IWeiboHandler;
import com.sina.weibo.sdk.api.share.IWeiboShareAPI;
import com.sina.weibo.sdk.api.share.SendMultiMessageToWeiboRequest;
import com.sina.weibo.sdk.auth.AuthInfo;
import com.sina.weibo.sdk.auth.Oauth2AccessToken;
import com.sina.weibo.sdk.constant.WBConstants;
import com.sina.weibo.sdk.utils.Utility;
import com.tencent.connect.share.QQShare;
import com.tencent.mm.sdk.modelmsg.SendMessageToWX;
import com.tencent.mm.sdk.modelmsg.WXMediaMessage;
import com.tencent.mm.sdk.modelmsg.WXWebpageObject;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import com.xgkj.diyiketang.EatShowApp;
import com.xgkj.diyiketang.ProtocolConst;
import com.xgkj.diyiketang.R;
import com.xgkj.diyiketang.activity.BaseActivity;
import com.xgkj.diyiketang.activity.WbcallbackActivity;
import com.xgkj.diyiketang.activity.data.AudieceAdapter;
import com.xgkj.diyiketang.activity.data.LiveLiuYanAdapter;
import com.xgkj.diyiketang.data.AudieceInfo;
import com.xgkj.diyiketang.data.DynamicInfo;
import com.xgkj.diyiketang.data.EatShowUserInfo;
import com.xgkj.diyiketang.data.LiveParentInfo;
import com.xgkj.diyiketang.http.engine.ShowToastTaskEventListener;
import com.xgkj.diyiketang.task.IsHaveLiveCoverTask;
import com.xgkj.diyiketang.task.LiveCommentTask;
import com.xgkj.diyiketang.task.LiveDetailTask;
import com.xgkj.diyiketang.task.LiveDynamicTask;
import com.xgkj.diyiketang.task.LiveOverTask;
import com.xgkj.diyiketang.task.StartLiveTask;
import com.xgkj.diyiketang.task.UpYZBUserIdTask;
import com.xgkj.diyiketang.task.UploadImage;
import com.xgkj.diyiketang.util.AccessTokenKeeper;
import com.xgkj.diyiketang.util.DateTimePickDialogUtil;
import com.xgkj.diyiketang.util.DialogUtil;
import com.xgkj.diyiketang.util.EatShowSetting;
import com.xgkj.diyiketang.util.GetImagePathUtil;
import com.xgkj.diyiketang.util.ImageCache;
import com.xgkj.diyiketang.util.LogUtils;
import com.xgkj.diyiketang.util.PalLog;
import com.xgkj.diyiketang.util.ToastUtil;
import com.xgkj.diyiketang.util.ViewUtil;
import com.xgkj.diyiketang.util.WeixinShareUtil;
import com.xgkj.diyiketang.util.zoom.DateUtil;
import com.xgkj.diyiketang.weidget.ClearableEditText;
import com.xgkj.diyiketang.weidget.GifView;
import com.xgkj.diyiketang.weidget.HorizontalGridView;
import com.xgkj.diyiketang.weidget.MoneyInputEditText;
import com.xgkj.diyiketang.weidget.RoundImageView;
import com.xgkj.diyiketang.yizhibo.been.LiveOption;
import com.xgkj.eatshow.wxapi.WXEntryActivity;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.ref.SoftReference;
import java.net.URLDecoder;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import pl.droidsonroids.gif.GifDrawable;
import pl.droidsonroids.gif.GifImageView;

public class RecorderNewActivity extends BaseActivity implements IWeiboHandler.Response, View.OnClickListener, LiveLiuYanAdapter.LiwuListener {
    private static final String TAG = "RecorderActivity";
    private MyHandler mHandler;
    private View mOptionsView;
    private Dialog mNetworkInvalidDialog;
    private Dialog mConfirmStopDialog;
    private Dialog mVideoStoppedDialog;
    private long mStartTime;
    private String mVid;
    private String mLiveTitle;
    private String imageId;
    private String titleString;
    private int startLiveTaskId = -1;
    private int getAnchorTaskId = -1;
    private int getDynamicListTaskId = -1;
    private ImageView mZhuBoImg;
    private TextView mZhuBoNick;
    private TextView mGuankanshu;
    EatShowUserInfo userinfo;
    //    HorizontalScrollView horizontalScrollView;
    HorizontalGridView mAudieGridList;
    //    DisplayMetrics dm;
//    private int NUM = 5; // 每行显示个数
//
//    private int LIEWIDTH;//每列宽度
//    private int LIE = 20;//列数
    private List<DynamicInfo> dynamicList;
    private List<AudieceInfo> audienceList;
    private AudieceAdapter adapter;
    private ListView lyListView;
    private LiveLiuYanAdapter lyAdapter;
    private ImageView huifuBtn;
    private LinearLayout huifuLayout;
    private RelativeLayout mCaoZuoLayout;
    private EditText mPingLunEdit;
    private Button mPingLunBtn;
    private String cmtText;
    private int cmtTaskId = -1;
    //    private Timer timer;
//    private Context mContext;
    private String curtime;
    private String dynamciTime;
    private ImageView mCloseView;
    private int overTaskId = -1;
    private String mYZBUserId;
    private int upYZbuseridTaskId = -1;
    private ImageView mShareImg;
    private PopupWindow popWindow;
    private String share_path;
    private Context mContext;
    private WeixinShareReceive mWeixinShareReceive;
    private String weixinsharetype;
    private String weixinuseropenid;
    private String weibouserid;
    private Bitmap weiboShareBitmap;
    private byte[] weixinshareByte;
    private IWXAPI api;
    private String type;
    private IWeiboShareAPI mWeiboShareAPI = null;
    private String shoucangtype;
    public static Tencent mTencent;
    private String share_title;
    private RelativeLayout mAllLayout, record_rl_gone;
    private int uploadImageTaskId = -1;
    private int ishavecoverTaskId = -1;
    private int yuyueLiveTaskId = -1;
    private String mBusinessId;
    private InputMethodManager in;
    //加了直播类型
    private int liveType = 0;
    private String charge_amount;
    private String live_pwd;
    private int liveIsOpen = 1;
    private int isXubo;
    private String descString;
    private TextView liveCateText;
    private String liveCateString;
    private String zhiboId;
    private Button zhiboDescBtn;
    private PopupWindow descPopWindow;
    private PopupWindow boPopWindow;
    private TextView desc_title;
    private TextView desc_content;
    private EditText yuyuestartTime;
    private PopupWindow stopPopWindow;
    private PopupWindow setPopwindow;
    private PopupWindow premissionPop;
    private File mFile;
    private static final int CAMERA_REQUEST = 0;
    private static final int CHOOSE_REQUEST = 11;
    private static final int CROP_REQUEST = 2;
    private static final int CHOOSE_IMG_REQUEST = 3;
    static final int RESULT_CODE_TITLE = 111;
    private CameraPreview mCameraPreview;
    private CameraTextureView mCamTextureView;
    private EVLive mEVLive;
    private View mCameraViewFrame;
    private View mTextureViewFrame;
    private EVBgmPlayer mEVBgmPlayer;
    private PowerManager.WakeLock mWakeLock;
    private String mBgmFilePath;
    private LiveOption mliveOption;
    private String headLogo;
    SimpleDateFormat df;
    private final static int PERMISSION_REQUEST_CAMERA_AUDIOREC = 1;
    private String initDateTime = "2016年05月12日 11:00"; //= "2016年4月29日 11:00"; // 初始化开始时间
    private HeadsetIntentReceiver mReceiver;
    private static final String CAMERA_FILE = "chibo/img";
    public static final String EXTRA_LIVE_CONFIG_BEAN = "extra_live_config_bean";
    private static final String BGM_FILE_NAME = "bgm.mp3";
    private static final float BGM_VOLUME = 1.0f;
    private static final int REQUEST_CODE_REGISTER = 1;
    private static final int MSG_REFRESH_START_TIME = 101;
    private String mKey;
    private String lid;
    private String uri;
    private Intent intent;
    private String local_url;
    private String up_img_url;
    private String coverUrl;
    private ImageView closeBtn;
    private String mYzbUserId;
    private String mKaishiTime;
    private long l;
    private DateFormat df_time;
    private String time_num;
    private String start_time;
    private PopupWindow botTitleWindow;
    private PopupWindow botDescWindow;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
//        mliveOption = (LiveOption) getIntent().getSerializableExtra(EXTRA_LIVE_CONFIG_BEAN);
//        if (true) {
//            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
//        } else {
//            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
//        }
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_recorder);
        mContext = this;
        getEVLiveid();
//        if (intent != null){
//            mBusinessId = intent.getStringExtra("BUSINESSID");
//        }
        in = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        mTencent = Tencent.createInstance(ProtocolConst.QQ_ID, this.getApplicationContext());
        api = WXAPIFactory.createWXAPI(mContext, ProtocolConst.APP_ID);
        File folder = EatShowSetting.getInstance(mContext).getDataFolder(CAMERA_FILE);
        String fileName = "IMG" + System.currentTimeMillis() + ".jpeg";
        mFile = new File(folder, fileName);
        df = new SimpleDateFormat("yyyy年MM月dd日 HH:mm");//设置日期格式
        mHandler = new MyHandler(this);
        initUIComponents();
        initListeners();
        initEVLive();
        mReceiver = new HeadsetIntentReceiver();
//        if (mliveOption.isBgmMix()) {
        if (false) {
            mEVBgmPlayer = EVBgmPlayer.getInstance();
            mEVBgmPlayer.setOnBgmPlayerListener(new EVBgmPlayer.OnBgmPlayerListener() {
                @Override
                public void onComplete() {

                }

                @Override
                public void onError(int err) {

                }
            });
            mEVBgmPlayer.setVolume(BGM_VOLUME);
        }
        Thread.currentThread().setName("main thread");
    }

    private void getEVLiveid() {
        final long start = System.currentTimeMillis();
        ApiHelper.getInstance(getApplicationContext()).getStream(new MyRequestCallBack<StreamInfoEntity>() {
            @Override
            public void onSuccess(String url, StreamInfoEntity result) {
                Logger.d(TAG, "genstream delay: " + (int) (System.currentTimeMillis() - start));
                lid = result.getLid();
                mKey = result.getKey();
                if (TextUtils.isEmpty(lid)) {
                    share_path = "http://115.28.236.67:8096/classroom/live.html?vid=" + lid + "";
                }
            }

            @Override
            public void onError(String url, int errorCode, String errorInfo) {
                ToastUtil.showMessage(RecorderNewActivity.this, "获取视频lid失败");
                super.onError(url, errorCode, errorInfo);
                finish();
            }

            @Override
            public void onFailure(String url, String msg) {
                ToastUtil.showMessage(RecorderNewActivity.this, "获取视频lid失败");
                finish();
            }
        });
    }

    //初始化直播模块
    private void initEVLive() {
        mEVLive = new EVLive(RecorderNewActivity.this);
        EVStreamerParameter.Builder builder = new EVStreamerParameter.Builder();
        builder.setVideoResolution(LiveConstants.VIDEO_RESOLUTION_360P)
                .setInitVideoBitrate(500)
                .setAudioBitrate(LiveConstants.AUDIO_BITRATE_32K)
                .setAudioCodec(LiveConstants.AUDIO_CODEC_AAC_LC)
                .setUseFrontCamera(true)
                .setIsBeautyOn(false)
                .setPortrait(true);
        mEVLive.setParameter(builder.build());
        mEVLive.setCameraPreview(mCameraPreview);
        //设置错误、信息回调
        mEVLive.setOnErrorListener(mErrorListener);
        mEVLive.setOnInfoListener(mInfoListener);
        mEVLive.onCreate();
//        int cameraPerm = ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA);
//        int audioPerm = ActivityCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO);
//        if (cameraPerm != PackageManager.PERMISSION_GRANTED ||
//                audioPerm != PackageManager.PERMISSION_GRANTED) {
//            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
//                Log.e(TAG, "No CAMERA or AudioRecord permission, please check");
//            } else {
//                String[] permissions = {Manifest.permission.CAMERA,
//                        Manifest.permission.RECORD_AUDIO,
//                        Manifest.permission.READ_EXTERNAL_STORAGE};
//                ActivityCompat.requestPermissions(this, permissions,
//                        PERMISSION_REQUEST_CAMERA_AUDIOREC);
//            }
//        } else {
//            //调用SDK对应的onCreate函数
//            mEVLive.onCreate();
//        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mHandler.removeMessages(MSG_REFRESH_START_TIME);
        mHandler.removeMessages(111);
        if (null != mEVLive) {
            mEVLive.onDestroy();
        }
    }

    public void startPhotoZoom(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            local_url = GetImagePathUtil.getPath(mContext, uri);
            uri = Uri.fromFile(new File(local_url));
        }
        intent.setDataAndType(uri, "image/*");
        // crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 100);
        intent.putExtra("outputY", 100);
        intent.putExtra("scale", true);
        intent.putExtra("return-data", false);
        intent.putExtra("scale", true);//黑边
        intent.putExtra("scaleUpIfNeeded", true);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mFile));
        startActivityForResult(intent, CROP_REQUEST);
//        setResult(CROP_REQUEST,intent );
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case REQUEST_CODE_REGISTER:
                if (null != data) {
                    if (!TextUtils.isEmpty(lid)) {
                        if (null != mEVLive) {
                            mEVLive.setOnErrorListener(mErrorListener);
                            mEVLive.setOnInfoListener(mInfoListener);
                            mEVLive.startStreaming(lid, mKey);
                        }
                    }
                }
                break;
            case CAMERA_REQUEST:
                if (!mFile.exists()) {
                    return;
                }
                Uri uri = Uri.fromFile(mFile);
                startPhotoZoom(uri);
//                uploadImage(mFile.getAbsolutePath());
                break;

            case CHOOSE_REQUEST:
                if (resultCode != RESULT_OK) {
                    return;
                }
                if (data == null)
                    return;
                Uri choose_uri = data.getData();
                startPhotoZoom(choose_uri);
                fengmian_gone.setVisibility(View.GONE);
//                setPopwindow.update();
                break;
            case CHOOSE_IMG_REQUEST:
                if (resultCode == 2) {
                    up_img_url = data.getStringExtra("Url");
                    imageId = data.getStringExtra("iamgeUrl");
                    if (up_img_url != null && up_img_url.length() > 0) {
                        ImageCache.getInstance(mContext).loadBitmapToView(fengmian, up_img_url, new ViewUtil.Size(ViewUtil.dip2px(mContext, 200), ViewUtil.dip2px(mContext, 200)));
                        fengmian_gone.setVisibility(View.GONE);
                    }
                }
                break;
            case CROP_REQUEST:
                if (resultCode != RESULT_OK) {
                    return;
                }
                if (data == null)
                    return;
                if (!mFile.exists()) {
                    return;
                }
                uploadImage(mFile.getAbsolutePath());
                break;
            case 300:
                PalLog.e("返回resultcode", resultCode + "");
                break;

            default:
                break;
        }
        if (RESULT_CODE_TITLE == resultCode && data != null) {
            setResult(RESULT_OK, data);
            Bundle bundle = data.getBundleExtra("bundle");
            String title = bundle.getString("TITLE");
//            if (null != title) {
//                mTitleText.setText(title);
//            }
        }
    }

    //上传图片
    private void uploadImage(String path) {
        UploadImage task = new UploadImage(path);
        task.addListener(new MyListener(this));
        uploadImageTaskId = getEatShowApp().getTaskManager().addTask(task);
    }

    private float currentX, currentY, scrollX, scrollY;

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            currentX = event.getRawX();
            currentY = event.getRawY();
        } else if (event.getAction() == MotionEvent.ACTION_MOVE) {
            scrollX = event.getRawX();
            scrollY = event.getRawY();
        } else if (event.getAction() == MotionEvent.ACTION_CANCEL || event.getAction() == MotionEvent.ACTION_UP) {

        }
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            if (getCurrentFocus() != null && getCurrentFocus().getWindowToken() != null) {
                in.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
        return super.onTouchEvent(event);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.

        return super.onOptionsItemSelected(item);
    }

    private OnErrorListener mErrorListener = new OnErrorListener() {
        @Override
        public boolean onError(int what) {
            switch (what) {
                case LiveConstants.EV_LIVE_ERROR_VERSION_LOW:
                    ToastUtil.showMessage(RecorderNewActivity.this, "当前系统版本太低，暂不支持该功能");
//                    showErrorToast(R.string.title_version_not_supported);
                    finish();
                    break;
                case LiveConstants.EV_LIVE_ERROR_OPEN_CAMERA:
                    ToastUtil.showMessage(RecorderNewActivity.this, R.string.title_call_camera_error);
                    finish();
                    break;
                case LiveConstants.EV_LIVE_ERROR_CREATE_AUDIORECORD:
                    ToastUtil.showMessage(RecorderNewActivity.this, R.string.title_audio_record_error);
                    finish();
                    break;
                case LiveConstants.EV_LIVE_ERROR_STARTING:
                    break;
                case LiveConstants.EV_LIVE_ERROR_RECONNECT:
                    mHandler.removeMessages(MSG_REFRESH_START_TIME);
                    showNetworkInvalidDialog();

                    break;
                case LiveConstants.EV_LIVE_ERROR_VIDEO_ALREADY_STOPPED:
                    if (isFinishing()) {
                        return true;
                    }
                    Dialog dialog = Utils.getOneButtonDialog(RecorderNewActivity.this,
                            getString(R.string.dialog_title_live_stop), false, false,
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    setResult(RESULT_OK);
                                    finish();
                                }
                            });
                    dialog.show();

                    break;
                case LiveConstants.EV_LIVE_ERROR_SDK_INIT:
                    ToastUtil.showMessage(RecorderNewActivity.this, R.string.msg_sdk_init_error);
                    finish();
                    break;
                case LiveConstants.EV_LIVE_PUSH_LOCATE_ERROR:
                    ToastUtil.showMessage(RecorderNewActivity.this, R.string.msg_push_locate_error);
                    finish();
                    break;
                case LiveConstants.EV_LIVE_PUSH_REDIRECT_ERROR:
                    ToastUtil.showMessage(RecorderNewActivity.this, R.string.msg_push_redirect_error);
                    finish();
                    break;
            }
            return true;
        }
    };
    private TextureView.SurfaceTextureListener mSurfaceTextureListener =
            new TextureView.SurfaceTextureListener() {
                @Override
                public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
                    if (mEVLive != null) {
                        Logger.w(TAG, "easyvaas-sdk-, onSurfaceTextureAvailable, visual width: " + width + ", visual height: " + height);
                        mEVLive.createPreview(surface, width, height);
                    }
                }

                @Override
                public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {
                    if (mEVLive != null) {
                        Logger.w(TAG, "easyvaas-sdk-, onSurfaceTextureSizeChanged, visual width: " + width + ", visual height: " + height);
                        mEVLive.updatePreview(width, height);
                    }
                }

                @Override
                public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
                    if (mEVLive != null) {
                        Logger.w(TAG, "easyvaas-sdk-, onSurfaceTextureDestroyed");
                        mEVLive.destroyPreview();
                    }

                    return true;
                }

                @Override
                public void onSurfaceTextureUpdated(SurfaceTexture surface) {

                }
            };

    private OnInfoListener mInfoListener = new OnInfoListener() {
        @Override
        public boolean onInfo(int what) {
            switch (what) {
                case LiveConstants.EV_LIVE_INFO_RECONNECTING:
                    if (isFinishing()) {
                        return true;
                    }
                    ToastUtil.showMessage(RecorderNewActivity.this, R.string.network_invalid_try_reconnect);
                    mHandler.removeMessages(MSG_REFRESH_START_TIME);

                    break;
                case LiveConstants.EV_LIVE_INFO_RECONNECTED:
                    if (isFinishing()) {
                        return true;
                    }
                    ToastUtil.showMessage(RecorderNewActivity.this, R.string.network_ok_message);
                    mHandler.sendEmptyMessage(MSG_REFRESH_START_TIME);

                    break;
                case LiveConstants.EV_LIVE_INFO_START_SUCCESS:
                    break;
                case LiveConstants.EV_LIVE_INFO_STREAMING:
                    break;
                case LiveConstants.EV_LIVE_INFO_STREAM_SUCCESS:
                    acquireWakeLock();
                    mStartTime = System.currentTimeMillis();

                    if (isFinishing()) {
                        return true;
                    }
//                    runOnUiThread(new Runnable() {
//                        @Override
//                        public void run() {
//                            doStart();
//                        }
//                    });
                    mHandler.sendEmptyMessage(MSG_REFRESH_START_TIME);
                    acquireWakeLock();
                    mStartTime = System.currentTimeMillis();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (isFinishing()) {
                                return;
                            }
                            mOptionsView.setVisibility(View.VISIBLE);
                            mHandler.sendEmptyMessage(MSG_REFRESH_START_TIME);
                        }
                    });
                    break;
            }
            return true;
        }
    };

    private void initUIComponents() {
        type = getIntent().getExtras().getString("FROM");
        record_rl_gone = (RelativeLayout) this.findViewById(R.id.record_rl_gone);
        mTextureViewFrame = (View) this.findViewById(R.id.texture_view_fl);
        mCameraViewFrame = (View) this.findViewById(R.id.camera_preview_fl);
        if (false) {
            mTextureViewFrame.setVisibility(View.VISIBLE);
            mCameraViewFrame.setVisibility(View.GONE);
            mCamTextureView = (CameraTextureView) this.findViewById(R.id.txv_preview);
            mCamTextureView.setKeepScreenOn(true);
            mCamTextureView.setSurfaceTextureListener(mSurfaceTextureListener);
            mCamTextureView.requestLayout();
        } else {
            mTextureViewFrame.setVisibility(View.GONE);
            mCameraViewFrame.setVisibility(View.VISIBLE);
            mCameraPreview = (CameraPreview) this.findViewById(R.id.camera_preview);
        }
        mAllLayout = (RelativeLayout) findViewById(R.id.all_layout);
        mZhuBoImg = (ImageView) findViewById(R.id.zhubo_img);
        mZhuBoNick = (TextView) findViewById(R.id.zhubo_nick);
        mGuankanshu = (TextView) findViewById(R.id.guankanshu);
//        horizontalScrollView = (HorizontalScrollView) findViewById(R.id.scrollView);
        mAudieGridList = (HorizontalGridView) findViewById(R.id.audie_list);
        adapter = new AudieceAdapter(this);
        mAudieGridList.setAdapter(adapter);
//        horizontalScrollView.setHorizontalScrollBarEnabled(false);// 隐藏滚动条
//        getScreenDen();
//        LIEWIDTH = dm.widthPixels / NUM;
        setValue();

        lyListView = (ListView) findViewById(R.id.liuyan_list);
        lyAdapter = new LiveLiuYanAdapter(mContext);
        lyAdapter.setLiwuListener(this);
        lyListView.setAdapter(lyAdapter);
        huifuBtn = (ImageView) findViewById(R.id.live_huifu);
        huifuBtn.setOnClickListener(this);
        huifuLayout = (LinearLayout) findViewById(R.id.huifu_layout);
        mAllLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (huifuLayout.getVisibility() == View.VISIBLE) {
                    huifuLayout.setVisibility(View.GONE);
                    huifuBtn.setVisibility(View.VISIBLE);
                    mCaoZuoLayout.setVisibility(View.VISIBLE);
                    mShareImg.setVisibility(View.VISIBLE);
                    try {
                        in.hideSoftInputFromWindow(RecorderNewActivity.this.getCurrentFocus().getWindowToken(), 0);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

            }
        });

        mCaoZuoLayout = (RelativeLayout) findViewById(R.id.live_options_right_ll);
        mPingLunEdit = (EditText) findViewById(R.id.pinglun);
        mPingLunBtn = (Button) findViewById(R.id.fabiaopinglun);
        mPingLunBtn.setOnClickListener(this);
        mCloseView = (ImageView) findViewById(R.id.recodr_guanbi);
        mCloseView.setOnClickListener(this);
        mShareImg = (ImageView) findViewById(R.id.live_share);
        mShareImg.setOnClickListener(this);
        mOptionsView = this.findViewById(R.id.live_options_right_ll);
//        liwuImageView = (GifView) findViewById(R.id.liwu_imageview);
        liwuImageView = (GifImageView) findViewById(R.id.liwu_imageview);
        liwuTanKuang = (LinearLayout) findViewById(R.id.liwutankuang);
        zhiboDescBtn = (Button) findViewById(R.id.zhibo_desc);
        zhiboDescBtn.setOnClickListener(this);
        initDescPopWindow();
        initPopWindow();
//        initBOPopWindow();
    }


    private OnInteractiveLiveListener mOnInteractiveLiveListener = new OnInteractiveLiveListener() {
        @Override
        public void onJoinChannelResult(boolean isSuccess) {

        }

        @Override
        public void onLeaveChannelSuccess() {
        }

        @Override
        public void onFirstRemoteVideoDecoded() {
            onInteractiveStart();
        }

        @Override
        public void onFirstLocalVideoFrame() {

        }

        @Override
        public void onUserOffline(int userId, int reason) {
            onInteractiveEnd();
        }

        @Override
        public void onError(int code, String message) {
        }
    };

    private void onInteractiveEnd() {

    }

    private void onInteractiveStart() {

    }

    private void setValue() {
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(adapter.getCount() * ViewUtil.dip2px(mContext, 32),
                ViewUtil.dip2px(mContext, 40));
        mAudieGridList.setLayoutParams(params);
        mAudieGridList.setColumnWidth(ViewUtil.dip2px(mContext, 32));
        mAudieGridList.setStretchMode(GridView.NO_STRETCH);
        int count = adapter.getCount();
        mAudieGridList.setNumColumns(count);
    }

    private void initListeners() {
        mOptionsView.findViewById(R.id.live_stop_iv).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isFinishing()) {
                    showConfirmStopDialog();
                }
            }
        });

        CheckBox cameraSwitchCb = (CheckBox) mOptionsView.findViewById(R.id.live_switch_camera_cb);
        cameraSwitchCb.setOnCheckedChangeListener(mOnCheckedChangeListener);

        CheckBox flashLightCb = (CheckBox) mOptionsView.findViewById(R.id.live_flash_cb);
        flashLightCb.setOnCheckedChangeListener(mOnCheckedChangeListener);
    }

    private CompoundButton.OnCheckedChangeListener mOnCheckedChangeListener =
            new CompoundButton.OnCheckedChangeListener() {

                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    switch (buttonView.getId()) {
                        case R.id.live_switch_camera_cb:
                            if (mEVLive != null) {
                                mEVLive.switchCamera();
                            }

                            CheckBox checkBox = (CheckBox) mOptionsView.findViewById(R.id.live_flash_cb);
                            checkBox.setEnabled(isChecked);
                            if (isChecked) {
                                checkBox.setChecked(false);
                            }
                            break;
                        case R.id.live_flash_cb:
                            if (mEVLive != null) {
                                mEVLive.switchFlashlight();
                            }
                            break;
                    }
                }
            };

    @Override
    protected void onResume() {
        super.onResume();
        doFresh();
        IntentFilter filter = new IntentFilter(Intent.ACTION_HEADSET_PLUG);
        registerReceiver(mReceiver, filter);
        super.onResume();
        if (null != mEVLive) {
            mEVLive.onResume();
            Logger.w(TAG, "easyvaas-sdk-, onResume");
            mHandler.sendEmptyMessage(MSG_REFRESH_START_TIME);
        }
    }

    @Override
    protected void onPause() {
        unregisterReceiver(mReceiver);
        super.onPause();
        // timer.cancel();
        if (null != mEVLive) {
            mEVLive.onPause();
            mHandler.removeMessages(MSG_REFRESH_START_TIME);
        }
        mHandler.removeMessages(111);
    }


    @Override
    public void onBackPressed() {
        showConfirmStopDialog();
    }

    private void showNetworkInvalidDialog() {
        if (isFinishing()) {
            return;
        }
        if (mNetworkInvalidDialog == null) {
            mNetworkInvalidDialog = Utils.getOneButtonDialog(this,
                    getResources().getString(R.string.no_network_dialog), false, false,
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            setResult(RESULT_OK);
                            finish();
                        }
                    });
        }
        mNetworkInvalidDialog.show();
    }

    private void showVideoStoppedDialog() {
        if (isFinishing()) {
            return;
        }
        if (mVideoStoppedDialog == null) {
            mVideoStoppedDialog = Utils.getOneButtonDialog(this,
                    getResources().getString(R.string.video_stopped_by_server_dialog), false, false,
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            setResult(RESULT_OK);
                            finish();
                        }
                    });
        }
        mVideoStoppedDialog.show();
    }

    private void showToastOnUiThread(final int resId) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (isFinishing()) {
                    return;
                }
                ToastUtil.showMessage(getApplicationContext(), resId);
                finish();
            }
        });
    }


    private Dialog mRegisterErrorDiaglog;

    private void showRegisterErrorDialog() {
        if (isFinishing()) {
            return;
        }

        if (mRegisterErrorDiaglog == null) {
            mRegisterErrorDiaglog = Utils.getOneButtonDialog(this, getResources().getString(R.string.already_register_but_error), false, false, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    setResult(RESULT_OK);
                    finish();
                }
            });
        }
        mRegisterErrorDiaglog.show();

    }

    private boolean isStart;

    private boolean checkInputStart() {
        if (null == zhiboId) {
            zhiboId = "";
        }
//        if (null == imageId) {
//            ToastUtil.showMessage(this, "请上传直播封面");
//            return false;
//        }

        if (TextUtils.isEmpty(neirong_et.getText())) {
            ToastUtil.showMessage(this, "请填写直播内容");
            return false;
        } else {
            descString = neirong_et.getText().toString();
        }
        if (null == mYZBUserId) {
            mYZBUserId = "";
        }
        if (TextUtils.isEmpty(liveCateString)) {
            ToastUtil.showMessage(this, "请选择直播类别");
            return false;
        }
        if (TextUtils.isEmpty(title_set.getText())) {
            ToastUtil.showMessage(this, "请填写直播标题");
            return false;
        } else {
            titleString = title_set.getText().toString();
        }

        isXubo = 0;
//        isXubo = intent.getIntExtra("isXubo", 0);
        if (liveType == 1) {
            if (TextUtils.isEmpty(chare_et.getText())) {
                ToastUtil.showMessage(this, "请输入收费金额");
                return false;
            } else {
                charge_amount = chare_et.getText().toString();
            }
        } else if (liveType == 2) {
            if (TextUtils.isEmpty(pwd_et.getText())) {
                ToastUtil.showMessage(this, "请输入密码");
                return false;
            } else {
                live_pwd = pwd_et.getText().toString();
            }
        }
        return true;
    }

    private void doStart() {
        isStart = true;
        StartLiveTask task = new StartLiveTask(lid, zhiboId, imageId, titleString, liveIsOpen, liveType, charge_amount, live_pwd, isXubo, null, liveCateString, descString, "1");
        task.addListener(new MyListener(this));
        startLiveTaskId = getEatShowApp().getTaskManager().addTask(task);
//        }
    }

    //预约直播
    private void doYuYue() {
        titleString = neirong_et.getText().toString();
        mKaishiTime = yuyuestartTime.getText().toString();
        descString = neirong_et.getText().toString();
//        if (fengmian.getDrawable() == null) {
//            Toast.makeText(mContext, "请上传您的直播封面", Toast.LENGTH_SHORT)
//                    .show();
//            return;
//        }
        if (TextUtils.isEmpty(titleString)) {
            Toast.makeText(mContext, "请输入直播标题", Toast.LENGTH_SHORT)
                    .show();
            return;
        }

        if (TextUtils.isEmpty(descString)) {
            Toast.makeText(mContext, "请输入直播内容介绍", Toast.LENGTH_SHORT)
                    .show();
            return;
        }


//        if (isOpenCheck.isChecked()) {
        liveIsOpen = 1;
//        } else {
//            liveIsOpen = 0;
//        }

        if (liveType == 1) {
            charge_amount = chare_et.getText().toString();
            if (ViewUtil.isNull(charge_amount)) {
                Toast.makeText(mContext, R.string.charge_amount_null, Toast.LENGTH_SHORT).show();
                return;
            }
            double amount_double = 0;

            try {
                amount_double = Double.parseDouble(charge_amount);
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
            if (amount_double <= 0) {
                Toast.makeText(mContext, R.string.charge_amount_null, Toast.LENGTH_SHORT).show();
                return;
            }

        } else if (liveType == 2) {
            live_pwd = pwd_et.getText().toString();
            if (ViewUtil.isNull(live_pwd)) {
                Toast.makeText(mContext, R.string.no_psw, Toast.LENGTH_SHORT).show();
                return;
            }
        }
        if (!ViewUtil.isNull(type) && type.equals("YUYUE")) {
            if (TextUtils.isEmpty(mKaishiTime)) {
                Toast.makeText(mContext, "请先选择开始时间", Toast.LENGTH_SHORT).show();
                return;
            }
        }
        StartLiveTask task = new StartLiveTask("", "", imageId, titleString, liveIsOpen, liveType, charge_amount, live_pwd, 0, mKaishiTime, liveCateString, descString, "1");
        task.addListener(new MyListener(this));
        yuyueLiveTaskId = getEatShowApp().getTaskManager().addTask(task);
    }

    private void doGetAnchorInfo() {
        LiveDetailTask dtask = new LiveDetailTask(lid);
        dtask.addListener(new MyListener(this));
        getAnchorTaskId = getEatShowApp().getTaskManager().addTask(dtask);
    }

    //获取直播封面
    private void doIsHaveLiveCover() {
        IsHaveLiveCoverTask coverTask = new IsHaveLiveCoverTask();
        coverTask.addListener(new MyListener(this));
        ishavecoverTaskId = getEatShowApp().getTaskManager().addTask(coverTask);
    }

    private void doLiveStop() {
        LiveOverTask overTask = new LiveOverTask(lid);
        overTask.addListener(new MyListener(this));
        overTaskId = getEatShowApp().getTaskManager().addTask(overTask);
    }

    private void getDynamicList() {
        if (dynamciTime == null) {
            Date date = new Date();
            DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            curtime = format.format(date);
            dynamciTime = curtime;
        }
        if (ViewUtil.isNull(lid)) {
            return;
        }
        if (getDynamicListTaskId != -1) {
            return;
        }
        PalLog.e("动态时间", curtime);
        LiveDynamicTask dyTask = new LiveDynamicTask(lid, dynamciTime, "20");
        dyTask.addListener(new MyListener(this));
        getDynamicListTaskId = getEatShowApp().getTaskManager().addTask(dyTask);
    }

    private int isLiveButton;

    class MyListener extends ShowToastTaskEventListener {

        private Date parse;
        private Date parse1;

        public MyListener(Context context) {
            super(context);
        }

        @Override
        public void handleTaskCompleted(int taskId, int result, Object data) {
            super.handleTaskCompleted(taskId, result, data);
            if (taskId == startLiveTaskId) {
                PalLog.e("直播开始", "直播开始......");
                doGetAnchorInfo();
//                Timer timer = new Timer();
//                timer.schedule(new TimerTask() {
//                    public void run() {
                Date date = new Date();
                DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                curtime = format.format(date);
                dynamciTime = curtime;
                getDynamicList();
//                Date curDate = new Date(System.currentTimeMillis());
//                String star_date = format.format(curDate);
//                format.parse(star_date);
//                    }
//                }, 2000);// 设定指定的时间time,此处为2000毫秒

            } else if (taskId == uploadImageTaskId) {
                uploadImageTaskId = -1;
                if (data != null) {
                    JSONObject json = (JSONObject) data;
                    headLogo = json.getString("imageURL");
                    if (headLogo != null && headLogo.length() > 0) {
                        fengmian.setVisibility(View.VISIBLE);
//                        uploadImgText.setVisibility(View.GONE);
//                        updateImg.setVisibility(View.GONE);
                        ImageCache.getInstance(mContext).loadBitmapToView(fengmian, headLogo, new ViewUtil.Size(ViewUtil.dip2px(mContext, 200), ViewUtil.dip2px(mContext, 200)));
                    }
                    imageId = json.getString("imageId");
                }
                if (mFile.exists()) {
                    mFile.delete();
                }
            } else if (taskId == ishavecoverTaskId) {

                JSONObject json = (JSONObject) data;
                coverUrl = json.getString("liveCoverUrl");
                mYzbUserId = json.getString("yiUserId");
                isLiveButton = json.getIntValue("isLiveButton");
                if (coverUrl != null && coverUrl.length() > 0) {
                    ImageCache.getInstance(mContext).loadBitmapToView(fengmian, coverUrl, new ViewUtil.Size(ViewUtil.dip2px(mContext, 100), ViewUtil.dip2px(mContext, 100)));
                    //mFengMianLayout.setOnClickListener(null);
//                    mFengmianBg.setVisibility(View.VISIBLE);
//                    uploadImgText.setVisibility(View.GONE);
//                    updateImg.setVisibility(View.GONE);
                }
                imageId = json.getString("imageId");
                titleString = json.getString("liveTitle");
                if (isLiveButton == 1) {
                    DialogUtil.createDialog(mContext, -1, getString(R.string.prompt), "您是否继续上次的直播", getString(R.string.ok), getString(R.string.cancel), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            setPopwindow.dismiss();
//                            Intent intent = new Intent(getApplicationContext(), RecorderNewActivity.class);
//                            intent.putExtra("YZBUSERID", mYzbUserId);
//                            intent.putExtra("isXubo", 1);
//                            intent.putExtra("TITLE", titleString);
//                            startActivity(intent);
//                            finish();
                        }
                    }, null);
                }
            } else if (taskId == yuyueLiveTaskId) {
                ToastUtil.showMessage(mContext, "预约直播成功！");
                setPopwindow.dismiss();
                finish();
            } else if (taskId == getAnchorTaskId) {
                userinfo = (EatShowUserInfo) data;
                if (userinfo != null) {
                    String liveContent = userinfo.getLiveContent();
                    try {
                        desc_title.setText(URLDecoder.decode(userinfo.getLiveTitle(), "utf-8"));
                        liveContent = URLDecoder.decode(liveContent, "utf-8");
                        desc_content.setText(liveContent);
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                    ImageCache.getInstance(mContext).loadBitmapToView(
                            mZhuBoImg,
                            userinfo.getUserLogo(),
                            new ViewUtil.Size(ViewUtil.dip2px(mContext, 32), ViewUtil.dip2px(
                                    mContext, 32)));
                    if (userinfo.getNickName() != null) {
                        try {
                            mZhuBoNick.setText(URLDecoder.decode(userinfo.getNickName(), "utf-8"));
                            share_title = URLDecoder.decode(userinfo.getNickName(), "utf-8") + "正在第一课堂直播，赶快点开吧！";
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }
                    }
                }
            } else if (taskId == getDynamicListTaskId) {
                getDynamicListTaskId = -1;
                LiveParentInfo lpInfo = (LiveParentInfo) data;
                mGuankanshu.setText(lpInfo.getViewCount() + "人");
                dynamicList = lpInfo.getDynamicList();
                if (dynamicList != null && dynamicList.size() > 0) {
                    lyAdapter.updateData(dynamicList);
                    lyListView.post(new Runnable() {
                        @Override
                        public void run() {
                            lyListView.smoothScrollToPosition(lyAdapter.getCount() - 1);
                        }
                    });
                    dynamciTime = dynamicList.get(dynamicList.size() - 1).getDynamicTime();
//                    PalLog.e("返回的动态时间", dynamciTime);
                }
                audienceList = lpInfo.getAudienceList();
                if (audienceList != null && audienceList.size() > 0) {
                    adapter.clearData();
                    adapter.updateData(audienceList);
                    setValue();
                }
            } else if (taskId == cmtTaskId) {
//                PalLog.e("评论成功", "lalala");
                DynamicInfo addInfo = new DynamicInfo();
                addInfo.setCommentContent(cmtText);
                addInfo.setUserName(EatShowApp.getInstance().getmUserInfo().getNickName());
                addInfo.setUserLevel(EatShowApp.getInstance().getmUserInfo().getUserLevel());
                addInfo.setDynamicType(1);
                List<DynamicInfo> dynamicList_self = new ArrayList<DynamicInfo>();
                dynamicList_self.add(addInfo);
                lyAdapter.updateData(dynamicList_self);
                lyListView.post(new Runnable() {
                    @Override
                    public void run() {
                        lyListView.setSelection(lyAdapter.getCount() - 1);
                    }
                });
            } else if (taskId == overTaskId) {
                EatShowUserInfo stop_info = (EatShowUserInfo) data;
                if (null != stop_info) {
                    if (!TextUtils.isEmpty(stop_info.getUserLogo())) {
                        ImageCache.getInstance(mContext).loadBitmapToView(zhubo_img, stop_info.getUserLogo(),
                                new ViewUtil.Size(ViewUtil.dip2px(mContext, 32), ViewUtil.dip2px(mContext, 32)));
                    }
                    Date date = new Date();
                    DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String ll = format.format(date);

                    try {
                        parse = format.parse(ll);
                        parse1 = format.parse(curtime);

                    } catch (ParseException e) {
                        e.printStackTrace();
                    }


                    long diff = parse.getTime() - parse1.getTime();

                    zhibo_stop_time.setText(DateUtil.formatInt((int) diff / 1000) + "");
//                    zhibo_stop_time.setText(DateUtil.formatDuring(diff) + "");
                    if (!TextUtils.isEmpty(stop_info.getFlower())) {
                        redflower_num.setText(stop_info.getFlower());
                    }
                    if (!TextUtils.isEmpty(stop_info.getViewCount())) {
                        person_num.setText(stop_info.getViewCount());
                    }
                    if (!TextUtils.isEmpty(stop_info.getBulletCout())) {
                        danmu_num.setText(stop_info.getBulletCout());
                    }

                }
                PalLog.e("第一课堂", "直播结束返回");
            } else if (taskId == upYZbuseridTaskId) {

                PalLog.e("第一课堂", "上传易直播Userid成功");
            }

        }

        @Override
        public void handleTaskError(int taskId, int errorCode, String errorMsg) {
            if (taskId == getDynamicListTaskId) {
                getDynamicListTaskId = -1;
                super.handleTaskError(taskId, errorCode, errorMsg);
            } else if (taskId == startLiveTaskId) {
                Log.e(TAG, "handleTaskError: " + errorCode);
                if (errorCode == 8000111 || errorCode == 8006001) {
                    DialogUtil.createDialog(mContext, getString(R.string.prompt), errorMsg, getString(R.string.ok), new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            liveStop(false);
                        }
                    });
                }
            } else {
                super.handleTaskError(taskId, errorCode, errorMsg);
            }
        }

        @Override
        public void handleTaskMessage(int taskId, Object data) {
            super.handleTaskMessage(taskId, data);
        }
    }

    ;

    private void saveLiveVideoInfo(String nickname, String title, String vid, String start_time) {
        List<Map<String, String>> oldDatas = Preferences.getInstance(getApplicationContext()).
                getList(Preferences.KEY_VIDEO_LIST);

        Map<String, String> newVideo = new HashMap<String, String>();
        newVideo.put(Constants.KEY_NICK_NAME, nickname);
        newVideo.put(Constants.KEY_TITLE, title);
        newVideo.put(Constants.KEY_VIDEO_ID, vid);
        newVideo.put(Constants.KEY_START_TIME, start_time);
        oldDatas.add(newVideo);

        Preferences.getInstance(getApplicationContext()).putList(Preferences.KEY_VIDEO_LIST, oldDatas);
    }

    private void initBOPopWindow() {
        View view = LayoutInflater.from(mContext).inflate(R.layout.pop_leibie, null);
        view.findViewById(R.id.beautiful_teacher).setOnClickListener(this);
        view.findViewById(R.id.youer).setOnClickListener(this);
        view.findViewById(R.id.k12).setOnClickListener(this);
        view.findViewById(R.id.techang).setOnClickListener(this);
        view.findViewById(R.id.jiatingjiaoyu).setOnClickListener(this);
        view.findViewById(R.id.naolijiaoyu).setOnClickListener(this);
        boPopWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = 0.5f; //0.0-1.0
        getWindow().setAttributes(lp);
//        ColorDrawable dw = new ColorDrawable(0x60000000);
        boPopWindow.setBackgroundDrawable(new ColorDrawable());
        boPopWindow.showAtLocation(view, Gravity.CENTER, 0, 0);
        boPopWindow.setFocusable(true);
        boPopWindow.setOutsideTouchable(true);
        boPopWindow.showAsDropDown(leibie_layout);
    }

    private void initZhiBoTitlePopWindow() {
        View view = LayoutInflater.from(mContext).inflate(R.layout.pop_zhibo_title, null);
        view.findViewById(R.id.text_1).setOnClickListener(this);
        view.findViewById(R.id.text_2).setOnClickListener(this);
        view.findViewById(R.id.text_3).setOnClickListener(this);
        view.findViewById(R.id.text_4).setOnClickListener(this);
        view.findViewById(R.id.text_5).setOnClickListener(this);
        view.findViewById(R.id.text_6).setOnClickListener(this);
        botTitleWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = 0.5f; //0.0-1.0
        getWindow().setAttributes(lp);
//        ColorDrawable dw = new ColorDrawable(0x60000000);
        botTitleWindow.setBackgroundDrawable(new ColorDrawable());
        botTitleWindow.showAtLocation(view, Gravity.CENTER, 0, 0);
        botTitleWindow.setFocusable(true);
        botTitleWindow.setOutsideTouchable(true);
        botTitleWindow.showAsDropDown(title_img);
    }

    private void initZhiBoDescPopWindow() {
        View view = LayoutInflater.from(mContext).inflate(R.layout.pop_zhibo_desc, null);
        view.findViewById(R.id.text_d_1).setOnClickListener(this);
        view.findViewById(R.id.text_d_2).setOnClickListener(this);
        view.findViewById(R.id.text_d_3).setOnClickListener(this);
        view.findViewById(R.id.text_d_4).setOnClickListener(this);
        view.findViewById(R.id.text_d_5).setOnClickListener(this);
        view.findViewById(R.id.text_d_6).setOnClickListener(this);
        botDescWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = 0.5f; //0.0-1.0
        getWindow().setAttributes(lp);
//        ColorDrawable dw = new ColorDrawable(0x60000000);
        botDescWindow.setBackgroundDrawable(new ColorDrawable());
        botDescWindow.showAtLocation(view, Gravity.CENTER, 0, 0);
        botDescWindow.setFocusable(true);
        botDescWindow.setOutsideTouchable(true);
        botDescWindow.showAsDropDown(title_img);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.text_1:
                botTitleWindow.dismiss();
                title_set.setText("万能的数学");
                break;
            case R.id.text_2:
                botTitleWindow.dismiss();
                title_set.setText("语言的魅力");
                break;
            case R.id.text_3:
                botTitleWindow.dismiss();
                title_set.setText("魔法英语");
                break;
            case R.id.text_4:
                botTitleWindow.dismiss();
                title_set.setText("政治理论");
                break;
            case R.id.text_5:
                botTitleWindow.dismiss();
                title_set.setText("历史知识");
                break;
            case R.id.text_6:
                botTitleWindow.dismiss();
                title_set.setText("地理文化");
                break;
            case R.id.text_d_1:
                botDescWindow.dismiss();
                neirong_et.setText("青春似火，超越自我。");
                break;
            case R.id.text_d_2:
                botDescWindow.dismiss();
                neirong_et.setText("要做no.1");
                break;
            case R.id.text_d_3:
                botDescWindow.dismiss();
                neirong_et.setText("知识改变命运");
                break;
            case R.id.text_d_4:
                botDescWindow.dismiss();
                neirong_et.setText("不让任何一名同学掉队");
                break;
            case R.id.text_d_5:
                botDescWindow.dismiss();
                neirong_et.setText("每天进步一点点");
                break;
            case R.id.text_d_6:
                botDescWindow.dismiss();
                neirong_et.setText("付出一定会有回报");
                break;

            case R.id.live_huifu:
                huifuLayout.setVisibility(View.VISIBLE);
                mCaoZuoLayout.setVisibility(View.GONE);
                huifuBtn.setVisibility(View.GONE);
                mShareImg.setVisibility(View.GONE);

                break;
            case R.id.fabiaopinglun:
                huifuLayout.setVisibility(View.GONE);
                huifuBtn.setVisibility(View.VISIBLE);
                mCaoZuoLayout.setVisibility(View.VISIBLE);
                mShareImg.setVisibility(View.VISIBLE);
                try {
                    in.hideSoftInputFromWindow(RecorderNewActivity.this.getCurrentFocus().getWindowToken(), 0);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (checkInput()) {
                    publishComment();
                    mPingLunEdit.setText(null);
                }
                break;
            case R.id.recodr_guanbi:
                if (!isFinishing()) {
                    showConfirmStopDialog();
                }
                break;
            case R.id.zhibo_stop_finish:
                stopPopWindow.dismiss();
                break;
            case R.id.live_share:
                popWindow.showAtLocation(v, Gravity.BOTTOM, 0, 0);
                break;

            case R.id.share_to_timeline:
                weixinsharetype = "sharefriends";
                shareToWeiXin(share_path, true);
                popWindow.dismiss();
                break;
            case R.id.share_to_weixinfriend:
                weixinsharetype = "sharefriend";
                shareToWeiXin(share_path, false);
                popWindow.dismiss();
                break;
            case R.id.share_to_weibo:
                shareToWeiBo(share_path);
                popWindow.dismiss();
                break;
            case R.id.share_to_qq:
                final Bundle params = new Bundle();
                params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_DEFAULT);
                params.putString(QQShare.SHARE_TO_QQ_TITLE, "第一课堂");
                params.putString(QQShare.SHARE_TO_QQ_SUMMARY, share_title);
                params.putString(QQShare.SHARE_TO_QQ_TARGET_URL, share_path);
                params.putString(QQShare.SHARE_TO_QQ_IMAGE_URL, "http://www.chiboker.com/diyiketangImage/diyiketang_icon.png");
                // params.putByteArray(QQShare.SHARE_TO_QQ_IMAGE_URL,weixinshareByte);
                params.putString(QQShare.SHARE_TO_QQ_APP_NAME, "第一课堂");
                mTencent.shareToQQ(this, params, qqShareListener);
                popWindow.dismiss();
                break;

            case R.id.zhibo_desc:
                descPopWindow.showAtLocation(v, Gravity.CENTER, 0, 0);
                break;
            case R.id.i_know:
                descPopWindow.dismiss();
            case R.id.fengmian_bg:
//                fengmian.setBackgroundResource(getResources().getColor());
                Intent choose_intent = new Intent();
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                    choose_intent.setAction(Intent.ACTION_OPEN_DOCUMENT);
                } else {
                    choose_intent.setAction(Intent.ACTION_GET_CONTENT);
                }
                choose_intent.setType("image/*");
                startActivityForResult(choose_intent, CHOOSE_REQUEST);
//                setResult( CHOOSE_REQUEST,choose_intent);
                break;
            //权限选择guanbi
            case R.id.upload_fengmian:
                getPremissionPopWindow();
                break;
            case R.id.close_btn_set:

                break;
            //预约发布按钮
            case R.id.yuyue_btn:
//                if (checkInput_toyuyue()){
                doYuYue();
//                }

                break;
            case R.id.set_title_more:
                if (boPopWindow != null && boPopWindow.isShowing()) {
                    boPopWindow.dismiss();
                }
                if (botDescWindow != null && botDescWindow.isShowing()) {
                    botDescWindow.dismiss();
                }
                initZhiBoTitlePopWindow();
//                descPopWindow.dismiss();
                break;
            case R.id.title_more:
                if (boPopWindow != null && boPopWindow.isShowing()) {
                    boPopWindow.dismiss();
                }
                if (botTitleWindow != null && botTitleWindow.isShowing()) {
                    botTitleWindow.dismiss();
                }
                initZhiBoDescPopWindow();

                break;
            case R.id.zhibo_set_free:
                liveType = 0;
                pwd_ll.setVisibility(View.GONE);
                money_num_ll.setVisibility(View.GONE);
                free_btn.setBackgroundResource(R.drawable.zhibo_set_btn);
                secrit_btn.setBackgroundResource(R.drawable.zhibo_set_btn_no);
                money_btn.setBackgroundResource(R.drawable.zhibo_set_btn_no);
                free_btn.setTextColor(getResources().getColor(R.color.shouye_tab_color_selected));
                secrit_btn.setTextColor(getResources().getColor(R.color.btn_answer_normal));
                money_btn.setTextColor(getResources().getColor(R.color.btn_answer_normal));
//                free_btn.setBackgroundResource(R.drawable.);
                break;
            case R.id.zhibo_set_money:
                liveType = 1;
                pwd_ll.setVisibility(View.GONE);
                money_num_ll.setVisibility(View.VISIBLE);
                money_btn.setBackgroundResource(R.drawable.zhibo_set_btn);
                secrit_btn.setBackgroundResource(R.drawable.zhibo_set_btn_no);
                free_btn.setBackgroundResource(R.drawable.zhibo_set_btn_no);
                free_btn.setTextColor(getResources().getColor(R.color.btn_answer_normal));
                secrit_btn.setTextColor(getResources().getColor(R.color.btn_answer_normal));
                money_btn.setTextColor(getResources().getColor(R.color.shouye_tab_color_selected));
                break;
            case R.id.zhibo_set_secrit:
                liveType = 2;
                pwd_ll.setVisibility(View.VISIBLE);
                money_num_ll.setVisibility(View.GONE);
                secrit_btn.setBackgroundResource(R.drawable.zhibo_set_btn);
                money_btn.setBackgroundResource(R.drawable.zhibo_set_btn_no);
                free_btn.setBackgroundResource(R.drawable.zhibo_set_btn_no);
                free_btn.setTextColor(getResources().getColor(R.color.btn_answer_normal));
                secrit_btn.setTextColor(getResources().getColor(R.color.shouye_tab_color_selected));
                money_btn.setTextColor(getResources().getColor(R.color.btn_answer_normal));

                break;
            //直播发布按钮
            case R.id.live_prepare_btn:
//                setPopwindow.update();
                if (checkInputStart()) {
                    setPopwindow.dismiss();
                    setPopwindow.setOnDismissListener(new poponDismissListener());
                    record_rl_gone.setVisibility(View.VISIBLE);
                    mEVLive.startStreaming(lid, mKey);
                    wuli_back = true;
                    doStart();
                }
                break;
            case R.id.starttime_layout:
                initDateTime = df.format(new Date());
                DateTimePickDialogUtil dateTimePicKDialog = new DateTimePickDialogUtil(
                        RecorderNewActivity.this, initDateTime);
                dateTimePicKDialog.dateTimePicKDialog(yuyuestartTime);
                break;
            case R.id.leibie_layout:
                if (botTitleWindow != null && botTitleWindow.isShowing()) {
                    botTitleWindow.dismiss();
                }
                if (descPopWindow != null && descPopWindow.isShowing()) {
                    descPopWindow.dismiss();
                }
                initBOPopWindow();
                break;
            case R.id.beautiful_teacher:
                boPopWindow.dismiss();
                liveCateText.setText("国学学院");
                liveCateString = "0a7a929a76ea44829672fe63733a5b42";
                break;
            case R.id.youer:
                liveCateText.setText("父母大学");
                liveCateString = "31d41764f6a24099a04bc1b614289f2c";
                boPopWindow.dismiss();
                break;

            case R.id.k12:
                liveCateText.setText("今日课表");
                liveCateString = "a10e3a144fd6412598c18796951386c1";
                boPopWindow.dismiss();
                break;
            case R.id.techang:
                liveCateText.setText("每日精彩");
                liveCateString = "d74604615a344df3bb4c569a40e16d28";
                boPopWindow.dismiss();
                break;
            case R.id.jiatingjiaoyu:
                liveCateText.setText("本周总结");
                liveCateString = "e9fa420b2d774965b80b48727fe3e968";
                boPopWindow.dismiss();
                break;
            case R.id.naolijiaoyu:
                liveCateText.setText("转运学院");
                liveCateString = "992a1f76047e4839a9631259c033d867";
                boPopWindow.dismiss();
                break;
            //公开
            case R.id.premission_public:
                pre_public.setImageResource(R.drawable.pitch_on);
                pre_benxiao.setImageResource(R.drawable.not);
                liveIsOpen = 1;
                break;
            //本校
            case R.id.premission_benxiao:
                pre_public.setImageResource(R.drawable.not);
                pre_benxiao.setImageResource(R.drawable.pitch_on);
                liveIsOpen = 0;
                break;
            //取消
            case R.id.premission_cancel:
                premissionPop.dismiss();
                break;
            //确定
            case R.id.premission_queding:
                premissionPop.dismiss();
                break;
        }
    }

    private void publishComment() {
        LiveCommentTask cmtTask = new LiveCommentTask(lid, cmtText);
        cmtTask.addListener(new MyListener(this));
        cmtTaskId = getEatShowApp().getTaskManager().addTask(cmtTask);
    }

    private void doUpYZBUserId() {
        if (ViewUtil.isNull(mYZBUserId)) return;
        UpYZBUserIdTask upTask = new UpYZBUserIdTask(mYZBUserId);
        upTask.addListener(new MyListener(this));
        upYZbuseridTaskId = getEatShowApp().getTaskManager().addTask(upTask);
    }

    private boolean checkInput() {
        cmtText = mPingLunEdit.getText().toString().trim();

        if (TextUtils.isEmpty(cmtText)) {
            Toast.makeText(mContext, R.string.no_cmt, Toast.LENGTH_SHORT)
                    .show();
            return false;
        }
        return true;
    }

    static class MyHandler extends Handler {
        private SoftReference<RecorderNewActivity> softReference;

        public MyHandler(RecorderNewActivity activity) {
            softReference = new SoftReference<RecorderNewActivity>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            RecorderNewActivity activity = softReference.get();
            if (activity == null) {
                return;
            }
            switch (msg.what) {
//                case MSG_REFRESH_START_TIME:
//                    activity.mDurationTv.setText(Utils.getDurationTime(activity, activity.mStartTime,
//                            System.currentTimeMillis()));
//                    sendEmptyMessageDelayed(MSG_REFRESH_START_TIME, 1000);
//                    break;
                case 111:
                    activity.getDynamicList();
//                    PalLog.e(TAG,"22222222222222222222222222222");
                    activity.mHandler.sendEmptyMessageDelayed(111, 2000);
                    break;
                case 333:
                    activity.hideDonghua();
                    break;
                case 444:
                    activity.hiddenView1();
                    break;
                case 555:
                    activity.hiddenView2();
                    break;
                case 2000:

                    break;
            }
        }
    }

    private void showConfirmStopDialog() {
        if (mConfirmStopDialog != null) {
            mConfirmStopDialog.show();
            return;
        }
        mConfirmStopDialog = new android.app.AlertDialog.Builder(this)
                .setTitle(R.string.title_confirm_stop_live)
                .setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        liveStop(true);

//                        stopPopwindow();
                    }
                })
                .setNegativeButton(R.string.cancel, null)
                .setOnKeyListener(new DialogInterface.OnKeyListener() {
                    @Override
                    public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP) {
                            dialog.dismiss();
                            return true;
                        }
                        return false;
                    }
                })
                .setCancelable(false)
                .create();
        mConfirmStopDialog.show();
    }

    private void liveStop(boolean isRequest) {
        releaseWakeLock();
        mHandler.removeMessages(MSG_REFRESH_START_TIME);
        if (mEVLive != null) {
//            if (mliveOption.isBgmMix()) {
            if (false) {
                mEVLive.stopBgmPlayer();
            }
            mEVLive.stopLive();
            mEVLive.onDestroy();
        }
//        stopPopwindow();
//        if (isRequest) {
//            doLiveStop();
//        }

//        if (wuli_back){
//            if (setPopwindow!=null){
//                setPopwindow.dismiss();
//                finish();
//            }
//        }else {
        stopPopwindow();
        if (isRequest) {
            doLiveStop();
        }
//        }
        setResult(RESULT_OK);
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus) {
            if (type.equals("ZHIBO")) {
                if (setPopwindow == null) {
                    record_rl_gone.setVisibility(View.GONE);
                    getSettingPopwindow(type);
                }
            } else if (type.equals("YUYUE")) {
                if (setPopwindow == null) {
                    record_rl_gone.setVisibility(View.GONE);
                    getSettingPopwindow(type);
                }
            }
        }
    }

    class poponDismissListener implements PopupWindow.OnDismissListener {

        @Override
        public void onDismiss() {
            // TODO Auto-generated method stub
            //Log.v("List_noteTypeActivity:", "我是关闭事件");
            WindowManager.LayoutParams lp = getWindow().getAttributes();
            lp.alpha = 1f; //0.0-1.0
            getWindow().setAttributes(lp);
        }

    }

    private ImageView fengmian, fengmian_gone, title_img, neirong_img, pression, guanbi;
    private EditText neirong_et, password, starttime_et, title_set;
    private Button live_prepare_btn, yuyue_btn, free_btn, money_btn, secrit_btn;
    private LinearLayout money_num_ll, pwd_ll;
    private MoneyInputEditText chare_et;
    private RelativeLayout starttime_rl, leibie_layout, zhibo_setting_ll;
    private ClearableEditText pwd_et;
    private TextView set_address;

    private void getSettingPopwindow(String type) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.activity_zhibo_setting, null);
        yuyue_btn = (Button) view.findViewById(R.id.yuyue_btn);
        set_address = (TextView) view.findViewById(R.id.fengmian_text);

        set_address.setText((TextUtils.isEmpty(EatShowApp.getACache().getAsString(Constants.USER_LOCATION)) ? "暂无定位" : (EatShowApp.getACache().getAsString(Constants.USER_LOCATION))));
        if (EatShowApp.getACache().getAsString("city") != null) {
            String city = EatShowApp.getACache().getAsString("city");
            set_address.setText(city);
        }
        fengmian = (ImageView) view.findViewById(R.id.fengmian_bg);
        fengmian_gone = (ImageView) view.findViewById(R.id.fengmian);
        guanbi = (ImageView) view.findViewById(R.id.close_btn_set);
        guanbi.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (setPopwindow != null && setPopwindow.isShowing()) {
                    setPopwindow.dismiss();
                }
                if (mEVLive != null) {
                    mEVLive.stopLive();
                    mEVLive.onDestroy();
                    RecorderNewActivity.this.finish();
                }
            }
        });
        title_img = (ImageView) view.findViewById(R.id.set_title_more);
        neirong_img = (ImageView) view.findViewById(R.id.title_more);
        pression = (ImageView) view.findViewById(R.id.upload_fengmian);
        neirong_et = (EditText) view.findViewById(R.id.hd_title);

        title_set = (EditText) view.findViewById(R.id.set_title);
        leibie_layout = (RelativeLayout) view.findViewById(R.id.leibie_layout);
        zhibo_setting_ll = (RelativeLayout) findViewById(R.id.zhibo_setting_ll);
//        starttime_et = (EditText) findViewById(R.id.starttime_content);
        live_prepare_btn = (Button) view.findViewById(R.id.live_prepare_btn);
        free_btn = (Button) view.findViewById(R.id.zhibo_set_free);
        money_btn = (Button) view.findViewById(R.id.zhibo_set_money);
        secrit_btn = (Button) view.findViewById(R.id.zhibo_set_secrit);
        money_num_ll = (LinearLayout) view.findViewById(R.id.charge_layout);
        chare_et = (MoneyInputEditText) view.findViewById(R.id.charge_edit);
        pwd_ll = (LinearLayout) view.findViewById(R.id.pwd_layout);
        pwd_et = (ClearableEditText) view.findViewById(R.id.password_edit);
        yuyuestartTime = (EditText) view.findViewById(R.id.starttime_content);
        starttime_rl = (RelativeLayout) view.findViewById(R.id.starttime_layout);
        liveCateText = (TextView) view.findViewById(R.id.leibie_content);

        leibie_layout.setOnClickListener(this);
        yuyue_btn.setOnClickListener(this);
        starttime_rl.setOnClickListener(this);
        live_prepare_btn.setOnClickListener(this);
        free_btn.setOnClickListener(this);
        money_btn.setOnClickListener(this);
        secrit_btn.setOnClickListener(this);
        fengmian.setOnClickListener(this);
        title_img.setOnClickListener(this);
        neirong_img.setOnClickListener(this);
        pression.setOnClickListener(this);
        if (type.equals("ZHIBO")) {
            yuyue_btn.setVisibility(View.GONE);
            starttime_rl.setVisibility(View.GONE);
        } else if (type.equals("YUYUE")) {
            yuyue_btn.setVisibility(View.VISIBLE);
            starttime_rl.setVisibility(View.VISIBLE);
            live_prepare_btn.setVisibility(View.GONE);
        }
        setPopwindow = new PopupWindow(view, WindowManager.LayoutParams.FILL_PARENT, WindowManager.LayoutParams.FILL_PARENT, true);
//        WindowManager.LayoutParams lp = getWindow().getAttributes();
//        lp.alpha = 0.5f; //0.0-1.0
//        getWindow().setAttributes(lp);
//        ColorDrawable dw = new ColorDrawable(0x60000000);
        setPopwindow.setBackgroundDrawable(new ColorDrawable());
        setPopwindow.showAtLocation(mAllLayout, Gravity.CENTER, 0, 0);
        LogUtils.i("setpop", setPopwindow);
    }

    RoundImageView zhubo_img;
    TextView danmu_num, person_num, redflower_num, zhibo_stop_time, zhibo_stop_finish;

    private void stopPopwindow() {
        View view = LayoutInflater.from(mContext).inflate(R.layout.zhibo_stop_pop, null);
        zhubo_img = (RoundImageView) view.findViewById(R.id.zhibostop_zhubo_img);
        zhubo_img.setType(1);
        danmu_num = (TextView) view.findViewById(R.id.zhibostop_danmu_num);
        person_num = (TextView) view.findViewById(R.id.zhibostop_person_num);
        redflower_num = (TextView) view.findViewById(R.id.zhibostop_redflower_num);
        zhibo_stop_time = (TextView) view.findViewById(R.id.zhibostop_time);
        zhibo_stop_finish = (TextView) view.findViewById(R.id.zhibo_stop_finish);
        ((ImageView) view.findViewById(R.id.zhibostop_weixin))
                .setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        ToastUtil.showMessage(RecorderNewActivity.this, "aaa");
                        weixinsharetype = "sharefriends";
                        shareToWeiXin(share_path, true);
                    }
                });
        ((ImageView) view.findViewById(R.id.zhibostop_friend_circle))
                .setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        ToastUtil.showMessage(RecorderNewActivity.this, "bbb");
                        weixinsharetype = "sharefriends";
                        shareToWeiXin(share_path, false);
                    }
                });
//        ((ImageView) view.findViewById(R.id.zhibostop_weibo))
//                .setOnClickListener(new View.OnClickListener() {
//                    @Override
//                    public void onClick(View v) {
//                        ToastUtil.showMessage(RecorderNewActivity.this, "ccc");
//                        shareToWeiBo(share_path);
//                    }
//                });
        ((ImageView) view.findViewById(R.id.zhibostop_qq))
                .setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        final Bundle params = new Bundle();
                        params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_DEFAULT);
                        params.putString(QQShare.SHARE_TO_QQ_TITLE, "第一课堂");
                        params.putString(QQShare.SHARE_TO_QQ_SUMMARY, share_title);
                        params.putString(QQShare.SHARE_TO_QQ_TARGET_URL, share_path);
                        params.putString(QQShare.SHARE_TO_QQ_IMAGE_URL, "http://www.chiboker.com/diyiketangImage/diyiketang_icon.png");
                        // params.putByteArray(QQShare.SHARE_TO_QQ_IMAGE_URL,weixinshareByte);
                        params.putString(QQShare.SHARE_TO_QQ_APP_NAME, "第一课堂");
                        mTencent.shareToQQ(RecorderNewActivity.this, params, qqShareListener);
                    }
                });
        ((ImageView) view.findViewById(R.id.zhibostop_zone))
                .setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        final Bundle params = new Bundle();
                        params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_DEFAULT);
                        params.putString(QQShare.SHARE_TO_QQ_TITLE, "第一课堂");
                        params.putString(QQShare.SHARE_TO_QQ_SUMMARY, share_title);
                        params.putString(QQShare.SHARE_TO_QQ_TARGET_URL, share_path);
                        params.putString(QQShare.SHARE_TO_QQ_IMAGE_URL, "http://www.chiboker.com/diyiketangImage/diyiketang_icon.png");
                        // params.putByteArray(QQShare.SHARE_TO_QQ_IMAGE_URL,weixinshareByte);
                        params.putString(QQShare.SHARE_TO_QQ_APP_NAME, "第一课堂");
                        mTencent.shareToQQ(RecorderNewActivity.this, params, qqShareListener);
                    }
                });
        stopPopWindow = new PopupWindow(view, WindowManager.LayoutParams.FILL_PARENT, WindowManager.LayoutParams.FILL_PARENT, true);
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = 0.6f; //0.0-1.0
        getWindow().setAttributes(lp);
        ColorDrawable dw = new ColorDrawable(0x60000000);
        stopPopWindow.setBackgroundDrawable(dw);
        stopPopWindow.showAtLocation(mAllLayout, Gravity.CENTER, 0, 0);
        stopPopWindow.setFocusable(true);
        zhibo_stop_finish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                stopPopWindow.dismiss();
                finish();
            }
        });
//        popWindow.setOutsideTouchable(true);
    }

    private void acquireWakeLock() {
        if (null == mWakeLock) {
            PowerManager pm = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
            mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, TAG);
        }

        if (!mWakeLock.isHeld()) {
            mWakeLock.acquire();
        }
    }

    private void releaseWakeLock() {
        if (null != mWakeLock) {
            mWakeLock.release();
            mWakeLock = null;
        }
    }


    private void doFresh() {
        //PalLog.e(TAG,"1111111111111111111111");
        mHandler.sendEmptyMessageDelayed(111, 2000);

//        timer = new Timer();
//        timer.schedule(new TimerTask() {
//            public void run() {
//                getDynamicList();
//            }
//        }, 2000);// 设定指定的时间time,此处为2000毫秒
    }

    private ImageView pre_public, pre_benxiao;

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case PERMISSION_REQUEST_CAMERA_AUDIOREC: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    mEVLive.onCreate();
                } else {
                    Log.e(TAG, "No CAMERA or AudioRecord permission");
//                    SingleToast.show(this, R.string.title_camera_audio_permission);
                }
                break;
            }
        }
    }

    private void startCameraPreviewWithPermCheck() {
        int cameraPerm = ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA);
        int audioPerm = ActivityCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO);
        if (cameraPerm != PackageManager.PERMISSION_GRANTED ||
                audioPerm != PackageManager.PERMISSION_GRANTED) {
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
                Log.e(TAG, "No CAMERA or AudioRecord permission, please check");
            } else {
                String[] permissions = {Manifest.permission.CAMERA,
                        Manifest.permission.RECORD_AUDIO,
                        Manifest.permission.READ_EXTERNAL_STORAGE};
                ActivityCompat.requestPermissions(this, permissions,
                        PERMISSION_REQUEST_CAMERA_AUDIOREC);
            }
        } else {
            mEVLive.onCreate();
            mEVLive.startStreaming(lid, mKey);
        }
    }

    private TextView cancle, queding;

    private void getPremissionPopWindow() {
        View view = LayoutInflater.from(mContext).inflate(R.layout.zhibo_premission_pop, null);
        pre_public = (ImageView) view.findViewById(R.id.premission_public);
        pre_public.setOnClickListener(this);
        pre_benxiao = (ImageView) view.findViewById(R.id.premission_benxiao);
        pre_benxiao.setOnClickListener(this);
        cancle = (TextView) view.findViewById(R.id.premission_cancel);
        cancle.setOnClickListener(this);
        queding = (TextView) view.findViewById(R.id.premission_queding);
        queding.setOnClickListener(this);
        premissionPop = new PopupWindow(view, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
        ColorDrawable colorDrawable = new ColorDrawable(getResources().getColor(R.color.white));
        premissionPop.setBackgroundDrawable(colorDrawable);
//        premissionPop.showAtLocation(zhibo_setting_ll, Gravity.CENTER, 0, 0);
        premissionPop.showAtLocation(mAllLayout, Gravity.CENTER, 0, 0);
        premissionPop.setFocusable(true);
        premissionPop.setOutsideTouchable(true);
    }

    private void initDescPopWindow() {
        View view = LayoutInflater.from(mContext).inflate(R.layout.pop_desc, null);
        TextView i_know = (TextView) view.findViewById(R.id.i_know);
        i_know.setOnClickListener(this);
        desc_title = (TextView) view.findViewById(R.id.title);
        desc_content = (TextView) view.findViewById(R.id.desc);
        descPopWindow = new PopupWindow(view, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        descPopWindow.setBackgroundDrawable(new ColorDrawable());
        descPopWindow.setFocusable(true);
        descPopWindow.setOutsideTouchable(true);
    }

    private void initPopWindow() {
        View view = LayoutInflater.from(mContext).inflate(R.layout.share_pop,
                null);
        ((ImageView) view.findViewById(R.id.share_to_timeline))
                .setOnClickListener(this);
        ((ImageView) view.findViewById(R.id.share_to_weixinfriend))
                .setOnClickListener(this);
        ((ImageView) view.findViewById(R.id.share_to_weibo))
                .setOnClickListener(this);
        ((ImageView) view.findViewById(R.id.share_to_qq))
                .setOnClickListener(this);
        popWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        popWindow.setBackgroundDrawable(new ColorDrawable());
        popWindow.setFocusable(true);
        popWindow.setOutsideTouchable(true);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
//        mWeiboShareAPI.handleWeiboResponse(intent, this);
    }

    @Override
    public void onResponse(BaseResponse baseResponse) {
        switch (baseResponse.errCode) {
            case WBConstants.ErrorCode.ERR_OK:
                Toast.makeText(this, R.string.weibosdk_toast_share_success,
                        Toast.LENGTH_LONG).show();
                //doShareWeiboGetPoint();
                break;
            case WBConstants.ErrorCode.ERR_CANCEL:
                Toast.makeText(this, R.string.weibosdk_toast_share_canceled,
                        Toast.LENGTH_LONG).show();
                break;
            case WBConstants.ErrorCode.ERR_FAIL:
                Toast.makeText(
                        this,
                        getString(R.string.weibosdk_toast_share_failed)
                                + "Error Message: " + baseResponse.errMsg,
                        Toast.LENGTH_LONG).show();
                break;
        }
    }

    class WeixinShareReceive extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            System.out.println(intent.getAction());
            weixinuseropenid = intent.getStringExtra(ProtocolConst.WEIXIN_OPENID);

            if (intent.getAction().equalsIgnoreCase(WXEntryActivity.WEIXIN_SHARE_SUCCESS_ACTION)) {

            } else if (intent.getAction().equalsIgnoreCase(WbcallbackActivity.WEIBO_SHARE_SUCCESS_ACTION)) {

            }
            if (mWeixinShareReceive != null) {
                unregisterReceiver(mWeixinShareReceive);
                mWeixinShareReceive = null;
            }
        }

    }

    IUiListener qqShareListener = new IUiListener() {
        @Override
        public void onCancel() {

        }

        @Override
        public void onComplete(Object response) {
            // TODO Auto-generated method stub
        }

        @Override
        public void onError(UiError e) {
            // TODO Auto-generated method stub

        }
    };


    private void shareToWeiXin(String shareUrl, boolean isTimeLine) {
        if (!api.isWXAppSupportAPI() || !api.isWXAppInstalled()) {
            Toast.makeText(mContext, R.string.need_weixin_app, Toast.LENGTH_SHORT).show();
            return;
        }

        if (mWeixinShareReceive != null) {
            unregisterReceiver(mWeixinShareReceive);
            mWeixinShareReceive = null;
        }

        if (mWeixinShareReceive == null) {
            mWeixinShareReceive = new WeixinShareReceive();
            IntentFilter filter = new IntentFilter();
            filter.addAction(WXEntryActivity.WEIXIN_SHARE_SUCCESS_ACTION);
            registerReceiver(mWeixinShareReceive, filter);
        }
        WXWebpageObject webPage = new WXWebpageObject();
        webPage.webpageUrl = shareUrl;
        WXMediaMessage msg = new WXMediaMessage(webPage);
        //msg.title = ppntitle;
        if (isTimeLine) {
            msg.title = share_title;
        } else {
            msg.title = "第一课堂";
        }
        msg.description = share_title;
        Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.app_icon);
        weixinshareByte = WeixinShareUtil.bmpToByteArray(bmp, true);
        if (weixinshareByte != null && weixinshareByte.length != 0) {
            msg.thumbData = weixinshareByte;
        }
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = buildTransaction("webpage");
        req.message = msg;
        req.scene = isTimeLine ? SendMessageToWX.Req.WXSceneTimeline
                : SendMessageToWX.Req.WXSceneSession;
        api.sendReq(req);
    }

    private String buildTransaction(final String type) {
        return (type == null) ? String.valueOf(System.currentTimeMillis())
                : type + System.currentTimeMillis();
    }

    private void shareToWeiBo(String webpage) {

        if (mWeixinShareReceive != null) {
            unregisterReceiver(mWeixinShareReceive);
            mWeixinShareReceive = null;
        }

        if (mWeixinShareReceive == null) {
            mWeixinShareReceive = new WeixinShareReceive();
            IntentFilter filter = new IntentFilter();
            filter.addAction(WbcallbackActivity.WEIBO_SHARE_SUCCESS_ACTION);
            registerReceiver(mWeixinShareReceive, filter);
        }

        WeiboMultiMessage weiboMessage = new WeiboMultiMessage();

        if (!TextUtils.isEmpty(webpage)) {
            TextObject textobject = new TextObject();
            textobject.text = "第一课堂";
            weiboMessage.textObject = textobject;
            WebpageObject mediaObject = new WebpageObject();
            mediaObject.identify = Utility.generateGUID();
            mediaObject.defaultText = "第一课堂";
            mediaObject.title = "第一课堂";
            mediaObject.description = share_title;
            mediaObject.actionUrl = webpage;
            if (weiboShareBitmap != null) {
                mediaObject.setThumbImage(weiboShareBitmap);
            } else {
                mediaObject.setThumbImage(BitmapFactory.decodeResource(
                        getResources(), R.drawable.app_icon));
            }
            weiboMessage.mediaObject = mediaObject;
        }

        SendMultiMessageToWeiboRequest request = new SendMultiMessageToWeiboRequest();
        // 用transaction唯一标识一个请求
        request.transaction = String.valueOf(System.currentTimeMillis());
        request.multiMessage = weiboMessage;

        // 3. 发送请求消息到微博，唤起微博分享界面
        AuthInfo authInfo = new AuthInfo(this, ProtocolConst.WEIBO_APP_KEY, ProtocolConst.WEIBO_REDIRECT_URL, ProtocolConst.WEIBO_SCOPE);
        Oauth2AccessToken accessToken = AccessTokenKeeper.readAccessToken(getApplicationContext());
        String token = "";
        if (accessToken != null) {
            token = accessToken.getToken();
            weibouserid = accessToken.getUid();
        }
//        mWeiboShareAPI.sendRequest(this, request, authInfo, token, new WeiboAuthListener() {
//
//
//            @Override
//            public void onWeiboException(WeiboException arg0) {
//            }
//
//            @Override
//            public void onComplete(Bundle bundle) {
//                Oauth2AccessToken newToken = Oauth2AccessToken.parseAccessToken(bundle);
//                AccessTokenKeeper.writeAccessToken(getApplicationContext(), newToken);
//                weibouserid = newToken.getUid();
////                    Toast.makeText(getApplicationContext(), "UID = "+weiboOpenId+"onAuthorizeComplete token = " + newToken.getToken(), 0).show();
//            }
//
//            @Override
//            public void onCancel() {
//            }
//        });


    }


    /**
     * 礼物相关
     */

    private View tankuangView1, tankuangView2;
    private ImageView headImage1, headImage2, liwuIcon1, liwuIcon2;
    private TextView dengjiText1, dengjiText2, shuliang1, shuliang2, liwuNick1, liwuNick2;
    private long view1time, view2time;
    private ObjectAnimator textScaleAnimation1;
    private ScaleAnimation textScaleAnimation2;
    private AnimationSet textAnimation;
    private LinearLayout liwuTanKuang;
    //    private ImageView liwuImageView;
//    private GifView liwuImageView;
    private GifImageView liwuImageView;


    private void hideDonghua() {
        liwuImageView.setVisibility(View.GONE);
        GifDrawable gifFromResource = (GifDrawable) liwuImageView.getDrawable();
        if (gifFromResource != null && !gifFromResource.isRecycled()) {
            gifFromResource.recycle();
        }
    }

    private void hiddenView1() {
        liwuTanKuang.removeView(tankuangView1);
        if (tankuangView2 != null && tankuangView2.getParent() != null) {
            liwuTanKuang.removeView(tankuangView2);
            liwuTanKuang.addView(tankuangView2);
        }
    }

    private void hiddenView2() {
        liwuTanKuang.removeView(tankuangView2);
    }

    private void showView1() {
        if (tankuangView1 != null && tankuangView1.getParent() == null) {
            liwuTanKuang.addView(tankuangView1);
        }
    }

    private void showView2() {
        if (tankuangView2 != null && tankuangView2.getParent() == null) {
            liwuTanKuang.addView(tankuangView2);
        }
    }

    private void initAnimation(View view) {
        textScaleAnimation1 = ObjectAnimator.ofFloat(view, View.SCALE_Y, 0.8f, 1.2f, 1f);
        textScaleAnimation1.setDuration(500);
        textScaleAnimation1.start();
    }


    private void tankuang(EatShowUserInfo info, String giftId, int count) {
        int liwuId = getResources().getIdentifier("t_" + giftId, "drawable", getPackageName());
        if (tankuangView1 == null) {
            tankuangView1 = LayoutInflater.from(mContext).inflate(R.layout.liwutankuang, liwuTanKuang, false);
            tankuangView1.setBackgroundResource(R.drawable.tankuang);
            headImage1 = (ImageView) tankuangView1.findViewById(R.id.head_img);

            dengjiText1 = (TextView) tankuangView1.findViewById(R.id.dengji);
            liwuNick1 = (TextView) tankuangView1.findViewById(R.id.nickname);
            liwuIcon1 = (ImageView) tankuangView1.findViewById(R.id.liwu_icon);
            shuliang1 = (TextView) tankuangView1.findViewById(R.id.count);
            shuliang1.getPaint().setShadowLayer(1, 2, 2, getResources().getColor(R.color.red));
            tankuangView1.setTag(info.getUserId());
            liwuTanKuang.addView(tankuangView1);
            mHandler.removeMessages(444);
            mHandler.sendEmptyMessageDelayed(444, 3000);
        }

        if (tankuangView2 == null && !info.getUserId().equals(tankuangView1.getTag())) {
            tankuangView2 = LayoutInflater.from(mContext).inflate(R.layout.liwutankuang, liwuTanKuang, false);
            tankuangView2.setBackgroundResource(R.drawable.tankuang);
            headImage2 = (ImageView) tankuangView2.findViewById(R.id.head_img);
            dengjiText2 = (TextView) tankuangView2.findViewById(R.id.dengji);
            liwuIcon2 = (ImageView) tankuangView2.findViewById(R.id.liwu_icon);
            shuliang2 = (TextView) tankuangView2.findViewById(R.id.count);
            shuliang2.getPaint().setShadowLayer(1, 2, 2, getResources().getColor(R.color.red));
            liwuNick2 = (TextView) tankuangView2.findViewById(R.id.nickname);
            tankuangView2.setTag(info.getUserId());
            liwuTanKuang.addView(tankuangView2);
            mHandler.removeMessages(555);
            mHandler.sendEmptyMessageDelayed(555, 3000);
        }

        if (info.getUserId().equals(tankuangView1.getTag())) {
            ImageCache.getInstance(mContext).loadBitmapToView(headImage1, info.getUserLogo(), ViewUtil.getHeadImageSize_40(mContext));
            dengjiText1.setText(info.getUserLevel());
            liwuIcon1.setImageResource(liwuId);
            liwuNick1.setText(URLDecoder.decode(info.getNickName()));
            count++;
            shuliang1.setText(getString(R.string.lianji_count, count));
            initAnimation(shuliang1);
            view1time = System.currentTimeMillis();
            showView1();
            mHandler.removeMessages(444);
            mHandler.sendEmptyMessageDelayed(444, 3000);

        } else if (info.getUserId().equals(tankuangView2.getTag())) {
            count++;
            ImageCache.getInstance(mContext).loadBitmapToView(headImage2, info.getUserLogo(), ViewUtil.getHeadImageSize_40(mContext));
            liwuIcon2.setImageResource(liwuId);
            dengjiText2.setText(info.getUserLevel());
            liwuNick2.setText(URLDecoder.decode(info.getNickName()));
            shuliang2.setText(getString(R.string.lianji_count, count));
            initAnimation(shuliang2);
            view2time = System.currentTimeMillis();
            showView2();
            mHandler.removeMessages(555);
            mHandler.sendEmptyMessageDelayed(555, 3000);
        } else {
            if (view1time > view2time) {
                count++;
                ImageCache.getInstance(mContext).loadBitmapToView(headImage2, info.getUserLogo(), ViewUtil.getHeadImageSize_40(mContext));
                dengjiText2.setText(info.getUserLevel());
                liwuIcon2.setImageResource(liwuId);
                liwuNick2.setText(URLDecoder.decode(info.getNickName()));
                shuliang2.setText(getString(R.string.lianji_count, count));
                initAnimation(shuliang2);
                tankuangView2.setTag(info.getUserId());
                view2time = System.currentTimeMillis();
                showView2();
                mHandler.removeMessages(555);
                mHandler.sendEmptyMessageDelayed(555, 3000);
            } else {
                count++;
                ImageCache.getInstance(mContext).loadBitmapToView(headImage1, info.getUserLogo(), ViewUtil.getHeadImageSize_40(mContext));
                dengjiText1.setText(info.getUserLevel());
                liwuIcon1.setImageResource(liwuId);
                liwuNick1.setText(URLDecoder.decode(info.getNickName()));
                shuliang1.setText(getString(R.string.lianji_count, count));
                initAnimation(shuliang1);
                tankuangView1.setTag(info.getUserId());
                view1time = System.currentTimeMillis();
                showView1();
                mHandler.removeMessages(444);
                mHandler.sendEmptyMessageDelayed(444, 3000);
            }
        }

        if (view1time > view2time) {
            liwuTanKuang.removeView(tankuangView1);
            liwuTanKuang.addView(tankuangView1);
        }

    }

    private GifView.OnStopListener stopListener = new GifView.OnStopListener() {
        @Override
        public void onStop() {
            hideDonghua();
        }
    };

    private void zuodonghua(EatShowUserInfo info, String giftId, int count) {
        tankuang(info, giftId, count);
        int gifUrl = 0;
        if (giftId.equals("0006")) {
            //礼盒
            gifUrl = R.raw.lihegif;

        } else if (giftId.equals("0007")) {
            //奖杯
            gifUrl = R.raw.jiangbei;
        } else if (giftId.equals("0014")) {
            //鲜花
            gifUrl = R.raw.xianhua;
        } else if (giftId.equals("0015")) {
            //笔记本
            gifUrl = R.raw.diannao;
        }

        if (gifUrl != 0) {
            if (liwuImageView.getVisibility() == View.VISIBLE) {
                return;
            }
            liwuImageView.setVisibility(View.VISIBLE);
            try {
                GifDrawable gifFromResource = new GifDrawable(getResources(), gifUrl);
                int frameint = gifFromResource.getDuration();
                liwuImageView.setImageDrawable(gifFromResource);
                mHandler.sendEmptyMessageDelayed(333, frameint);
            } catch (IOException e) {
                e.printStackTrace();
            }
//        if (gifUrl != 0) {
//            liwuImageView.setImageResource(-1);
//            if(liwuImageView.getVisibility()==View.VISIBLE){
//                return;
//            }
//            liwuImageView.setVisibility(View.VISIBLE);
//            liwuImageView.setMovieResource(gifUrl);
//            liwuImageView.setOnStopListener(stopListener);
           /* Glide.with(RecorderActivity.this).load(gifUrl).asGif().diskCacheStrategy(DiskCacheStrategy.NONE).listener(new RequestListener<Integer, GifDrawable>() {
                @Override
                public boolean onException(Exception e, Integer integer, Target<GifDrawable> target, boolean b) {
                    return false;
                }

                @Override
                public boolean onResourceReady(GifDrawable gifDrawable, Integer integer, Target<GifDrawable> target, boolean b, boolean b1) {
                    int duration = 0;
                    try {
                        GifDrawable gif = gifDrawable;
                        GifDecoder decoder = gif.getDecoder();
                        for (int i = 0; i < gif.getFrameCount(); i++) {
                            duration += decoder.getDelay(i);
                            if (i == gif.getFrameCount() - 1) {
                                PalLog.e(TAG, "gif张数：" + i);
                            }
                        }
                        PalLog.e(TAG, "gif时长：" + duration);
                    } catch (Throwable e) {
                    }
                    mHandler.removeMessages(333);
                    mHandler.sendEmptyMessageDelayed(333, duration * 5);
                    return false;
                }
            }).into((Target) new GlideDrawableImageViewTarget(liwuImageView, 1));
            */
        }
    }

    @Override
    public void adapterLiwu(EatShowUserInfo info, TextView textView, String giftId, int count, boolean isZx) {
        if (!isZx) {
            zuodonghua(info, giftId, count);
        }
        String giftName = getGiftName(giftId);
        textView.setTextColor(getResources().getColor(R.color.orange_public));
        textView.setText("送了一个" + giftName);
    }

    @Override
    public void OnLiveStop() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (isFinishing()) {
                    return;
                }
                Dialog dialog = Utils.getOneButtonDialog(RecorderNewActivity.this,
                        getString(R.string.dialog_title_live_stop), false, false,
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                setResult(RESULT_OK);
                                finish();
                            }
                        });
                dialog.show();
            }
        });
    }

    private boolean wuli_back = false;
    private long exitTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK &&
                event.getAction() == KeyEvent.ACTION_DOWN) {
            if (setPopwindow != null && setPopwindow.isShowing()) {
                setPopwindow.dismiss();
            }
            if (boPopWindow != null && boPopWindow.isShowing()) {
                boPopWindow.dismiss();
            }
            if (descPopWindow != null && descPopWindow.isShowing()) {
                descPopWindow.dismiss();
            }
            if (botTitleWindow != null && botTitleWindow.isShowing()) {
                botTitleWindow.dismiss();
            }
            if (botDescWindow != null && botDescWindow.isShowing()) {
                botDescWindow.dismiss();
            }

            if (mEVLive != null) {
                mEVLive.stopLive();
                mEVLive.onDestroy();
                RecorderNewActivity.this.finish();
            }
            return true;

        }
        return super.onKeyDown(keyCode, event);
    }

    //    @Override
// public boolean onKeyDown(int keyCode, KeyEvent event) {
//           // TODO Auto-generated method stub
//           if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
//               wuli_back = true;
//               exit();
//               return true;
//           }else {
//                   moveTaskToBack(true);
//           }
//        return super.onKeyDown(keyCode, event);
//    }
    private boolean isExit = false;

    public void exit() {
        if (!isExit) {
            isExit = true;
            if (mEVLive != null) {
                mEVLive.stopLive();
                mEVLive.onDestroy();
            }
            if (isFinishing()) {
                finish();
            }
            Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();
        } else {
            if (mEVLive != null) {
                mEVLive.stopLive();
                mEVLive.onDestroy();
            }
//            Intent intent = new Intent(Intent.ACTION_MAIN);
//            intent.addCategory(Intent.CATEGORY_HOME);
//            startActivity(intent);
            System.exit(0);
        }
    }

    private String getGiftName(String giftId) {
        String giftName = null;
        if (giftId.equals("0001")) {
            giftName = "气球";
        } else if (giftId.equals("0002")) {
            giftName = "小蘑菇";
        } else if (giftId.equals("0003")) {
            giftName = "冰淇淋";
        } else if (giftId.equals("0004")) {
            giftName = "喜欢你";
        } else if (giftId.equals("0005")) {
            giftName = "手表";
        } else if (giftId.equals("0006")) {
            giftName = "礼盒";
        } else if (giftId.equals("0007")) {
            giftName = "奖杯";
        } else if (giftId.equals("0008")) {
            giftName = "鼓掌";
        } else if (giftId.equals("0009")) {
            giftName = "棒棒糖";
        } else if (giftId.equals("0010")) {
            giftName = "咖啡";
        } else if (giftId.equals("0011")) {
            giftName = "手绘画";
        } else if (giftId.equals("0012")) {
            giftName = "地球仪";
        } else if (giftId.equals("0013")) {
            giftName = "金牌教师";
        } else if (giftId.equals("0014")) {
            giftName = "鲜花";
        } else if (giftId.equals("0015")) {
            giftName = "笔记本";
        }
        return giftName;
    }

    private class HeadsetIntentReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(Intent.ACTION_HEADSET_PLUG)) {
                int state = intent.getIntExtra("state", -1);
                switch (state) {
                    case 0:
                        if (mEVLive != null) {
                            mEVLive.setHeadsetPlugged(false);
                        }
                        Logger.d(TAG, "Headset is unplugged");
                        break;
                    case 1:
                        if (mEVLive != null) {
                            mEVLive.setHeadsetPlugged(true);
                        }
                        Logger.d(TAG, "Headset is plugged");
                        break;
                    default:
                        Logger.d(TAG, "I have no idea what the headset state is");
                }
            }
        }
    }
}
